from flask import Flask
from app.config import config
from app.extensions import db, migrate, login_manager, bootsrtap
from app.admin import users, site, auth
from flask_login import current_user
from app.cli import register_cli
from app.filter import register_filter
from app.api import api
import os


def create_app(config_class=None):
    if config_class is None:
        config_class = os.getenv('FLASK_CONFIG', 'development')
    app = Flask(__name__)
    app.config.from_object(config[config_class])

    register_buleprints(app)
    register_extensions(app)

    register_cli(app)
    register_template_context(app)
    register_filters(app)

    return app


# 注册蓝本
def register_buleprints(app):
    app.register_blueprint(site.bp)
    app.register_blueprint(auth.bp, url_prefix='/auth')
    app.register_blueprint(users.bp, url_prefix='/users')
    app.register_blueprint(api.bp, url_prefix='/api')


# 注册扩展
def register_extensions(app):
    bootsrtap.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)


# 注册过滤器
def register_filters(app):
    register_filter(app)



# 生成模板公共变量
def register_template_context(app):
    @app.context_processor
    def make_template_context():
        return dict(admin=current_user)
